import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
  // do something before request is sent
  console.log(16, config)
  if (store.getters.token && !config.url.includes('auth/local/register')) {
    console.log('网络请求', config)
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config
}
// ,
// error => {
//   // do something with request error
//   console.log(error) // for debug
//   return Promise.reject(error)
// }
)

// response interceptor
service.interceptors.response.use(response => {
  const res = response.data
  console.log(response)
  // Message.success('操作成功')
  return res
},
error => {
  console.log('err' + error) // for debug
  Message({
    message: error.message,
    type: 'error',
    duration: 5 * 1000
  })
  return Promise.reject(error)
}
)

export default service
